<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.addFriend.title')"
    width="600px"
    :before-close="handleClose"
  >
    <div class="add-friend-content">
      <!-- 搜索用户 -->
      <div class="search-section">
        <el-form @submit.prevent="handleSearch">
          <el-form-item :label="$t('contacts.search.searchUser')">
            <el-input
              v-model="searchForm.keyword"
              :placeholder="$t('contacts.search.searchPlaceholder')"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button 
                  type="primary" 
                  @click="handleSearch"
                  :loading="contactsStore.searchLoading"
                >
                  {{ $t('contacts.addFriend.searchButton') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item :label="$t('contacts.search.searchType')">
            <el-radio-group v-model="searchForm.searchType">
              <!-- {{ AURA-X: Modify - 修复Element Plus兼容性，将label改为value. Approval: 寸止(ID:fix-element-plus-radio). }} -->
              <el-radio value="ALL">{{ $t('contacts.search.searchTypes.all') }}</el-radio>
              <el-radio value="USERNAME">{{ $t('contacts.search.searchTypes.username') }}</el-radio>
              <el-radio value="EMAIL">{{ $t('contacts.search.searchTypes.email') }}</el-radio>
              <el-radio value="REAL_NAME">{{ $t('contacts.search.searchTypes.realName') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results" v-if="contactsStore.searchResults.length > 0">
        <h4 class="results-title">{{ $t('contacts.search.searchResults') }}</h4>
        <div class="user-list">
          <div 
            v-for="user in contactsStore.searchResults" 
            :key="user.id"
            class="user-item"
          >
            <div class="user-avatar">
              <el-avatar :src="user.avatarUrl" :size="40">
                {{ user.realName?.charAt(0) || user.username.charAt(0) }}
              </el-avatar>
            </div>
            
            <div class="user-info">
              <div class="user-name">
                {{ user.realName || user.username }}
                <el-tag v-if="user.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
                <el-tag v-if="user.userType === 'ADMIN'" type="danger" size="small">{{ $t('contacts.friend.userTypes.admin') }}</el-tag>
              </div>
              <div class="user-details">
                <span class="username">@{{ user.username }}</span>
                <span class="join-date">
                  {{ $t('contacts.friend.joinedAt') }} {{ formatDate(user.createdAt) }}
                </span>
              </div>
            </div>
            
            <div class="user-actions">
              <el-button 
                v-if="user.isFriend"
                disabled
                size="small"
              >
                {{ $t('contacts.friend.actions.alreadyFriend') }}
              </el-button>
              <el-button 
                v-else-if="user.hasPendingRequest"
                disabled
                size="small"
              >
                {{ $t('contacts.friend.actions.requestSent') }}
              </el-button>
              <el-button 
                v-else-if="user.canSendRequest"
                type="primary"
                size="small"
                @click="showSendRequest(user)"
              >
                {{ $t('contacts.actions.addFriend') }}
              </el-button>
              <el-button 
                v-else
                disabled
                size="small"
              >
                {{ $t('contacts.friend.actions.cannotAdd') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="hasSearched && !contactsStore.searchLoading" class="empty-results">
        <el-empty :description="$t('contacts.search.noResults')" />
      </div>

      <!-- 使用提示 -->
      <div v-if="!hasSearched" class="search-tips">
        <el-alert
          :title="$t('contacts.addFriend.searchTips')"
          type="info"
          :closable="false"
          show-icon
        >
          <ul>
            <li>{{ $t('contacts.addFriend.searchTip1') }}</li>
            <li>{{ $t('contacts.addFriend.searchTip2') }}</li>
            <li>{{ $t('contacts.addFriend.searchTip3') }}</li>
          </ul>
        </el-alert>
      </div>
    </div>

    <!-- 发送好友申请对话框 -->
    <el-dialog
      v-model="showRequestDialog"
      title="发送好友申请"
      width="400px"
      append-to-body
    >
      <el-form :model="requestForm" label-width="80px">
        <el-form-item label="申请对象">
          <div class="request-target">
            <el-avatar :src="selectedUser?.avatarUrl" :size="32">
              {{ selectedUser?.realName?.charAt(0) || selectedUser?.username.charAt(0) }}
            </el-avatar>
            <span class="target-name">
              {{ selectedUser?.realName || selectedUser?.username }}
            </span>
          </div>
        </el-form-item>
        
        <el-form-item label="申请消息">
          <el-input
            v-model="requestForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入申请消息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showRequestDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSendRequest"
          :loading="sendingRequest"
        >
          发送申请
        </el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useContactsStore } from '@/stores/contacts'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  searchType: 'ALL'
})

const requestForm = reactive({
  message: ''
})

const hasSearched = ref(false)
const showRequestDialog = ref(false)
const selectedUser = ref<any>(null)
const sendingRequest = ref(false)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 方法
const handleSearch = async () => {
  if (!searchForm.keyword.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    await contactsStore.searchUsers(
      searchForm.keyword,
      searchForm.searchType,
      true, // 排除已有好友
      0,
      20
    )
    hasSearched.value = true
  } catch (error) {
    console.error('搜索用户失败:', error)
  }
}

const showSendRequest = (user: any) => {
  selectedUser.value = user
  requestForm.message = `你好，我是${user.realName || user.username}，希望能成为好友`
  showRequestDialog.value = true
}

const handleSendRequest = async () => {
  if (!selectedUser.value) return

  try {
    sendingRequest.value = true
    
    await contactsStore.sendFriendRequest(
      selectedUser.value.id,
      requestForm.message
    )

    // 更新搜索结果中的状态
    const userIndex = contactsStore.searchResults.findIndex(
      u => u.id === selectedUser.value.id
    )
    if (userIndex > -1) {
      contactsStore.searchResults[userIndex].hasPendingRequest = true
      contactsStore.searchResults[userIndex].canSendRequest = false
    }

    showRequestDialog.value = false
    ElMessage.success('好友申请已发送')
    emit('success')
    
  } catch (error) {
    console.error('发送好友申请失败:', error)
  } finally {
    sendingRequest.value = false
  }
}

const handleClose = () => {
  // 清理搜索结果
  contactsStore.clearSearchResults()
  hasSearched.value = false
  searchForm.keyword = ''
  searchForm.searchType = 'ALL'
  
  visible.value = false
}

const formatDate = (dateString: string) => {
  try {
    return format(new Date(dateString), 'yyyy年MM月', { locale: zhCN })
  } catch {
    return '未知'
  }
}
</script>

<style scoped>
.add-friend-content {
  min-height: 300px;
}

.search-section {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.search-results {
  margin-bottom: 24px;
}

.results-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-list {
  max-height: 400px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  margin-bottom: 8px;
  transition: all 0.2s;
}

.user-item:hover {
  border-color: var(--el-color-primary);
  background: var(--el-fill-color-extra-light);
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.user-details {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.username {
  color: var(--el-color-primary);
}

.empty-results {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.search-tips {
  padding: 20px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.search-tips ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.search-tips li {
  margin-bottom: 4px;
  color: var(--el-text-color-regular);
}

.request-target {
  display: flex;
  align-items: center;
  gap: 8px;
}

.target-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}
</style>
